const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
require('dotenv').config();

// 获取项目名
const projectName = process.argv[2].split('+');

(async () => {
    for (const item of projectName) {
        const srcStr = '../src';
        const publicStr = '../public';
        const customSrcStr = `${srcStr}/custom/${item}`;
        const customPublicStr = `${customSrcStr}/public`;

        // Src 目录地址
        const srcPath = path.resolve(__dirname, srcStr);
        const customSrcPath = path.resolve(__dirname, customSrcStr);

        // Public 目录地址
        const publicPath = path.resolve(__dirname, publicStr);
        const customPublicPath = path.resolve(__dirname, customPublicStr);

        // 判断 custom 中相对应的项目是否存在
        if (!fs.existsSync(customSrcPath)) {
            throw new Error(`❌❌ ----- ${item}不存在，请检查后重试 ----- ❌❌`);
        } else {
            // 检查 custom 中是否存在 Public 目录，如果存在则将 Public 同步复制出去
            if (fs.existsSync(customPublicPath)) {
                await new Promise((resolve, reject) => {
                    fse.copy(customPublicPath, publicPath, (err) => {
                        if (err) return reject(err);
                        resolve();
                    });
                });
            }

            let message;
            if (projectName.length > 1) {
                message = `选定多个 CUSTOM ，开始复制：${item}`;
            } else {
                message = `选定 CUSTOM 为：${item ? item : '通用版'}`;
            }

            await new Promise((resolve, reject) => {
                fse.copy(customSrcPath, srcPath, (err) => {
                    if (err) return reject(err);
                    console.log('✨✨ -----', message, '----- ✨✨');
                    resolve();
                });
            });
        }
    }
})();
